using System;
using System.Drawing;
using System.Windows.Forms;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using System.Threading.Tasks;

namespace WindowsFormsDataBaice
{
    public class MedicalCardForm : Form
    {
        private Panel headerPanel;
        private Panel contentPanel;
        private Panel buttonPanel;
        
        // 当前用户信息
        private int currentUserId;
        private string currentUserName;
        
        // 表单控件
        private TextBox txtName;
        private RadioButton rbMale;
        private RadioButton rbFemale;
        private DateTimePicker dtpBirth;
        private TextBox txtContact;
        private TextBox txtIdCard;
        private TextBox txtAddress;
        private TextBox txtInfectionHistory;
        private TextBox txtGeneticInfo;
        private TextBox txtCreatePerson;
        
        // 标签
        private Label lblName;
        private Label lblSex;
        private Label lblBirth;
        private Label lblContact;
        private Label lblIdCard;
        private Label lblAddress;
        private Label lblInfection;
        private Label lblGenetic;
        private Label lblCreatePerson;
        
        // 按钮
        private Button btnSave;
        private Button btnCancel;
        private Button btnReset;

        public MedicalCardForm()
        {
            InitializeComponent();
            SetupEventHandlers();
        }

        public MedicalCardForm(int userId, string userName)
        {
            this.currentUserId = userId;
            this.currentUserName = userName;
            InitializeComponent();
            SetupEventHandlers();
        }

        private void InitializeComponent()
        {
            // 设置窗体基本属性
            this.Size = new Size(900, 700);
            this.Text = "医疗卡办理 - 新增患者信息";
            this.StartPosition = FormStartPosition.CenterScreen;
            this.BackColor = UIStyleManager.BackgroundColor;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;

            // 创建头部面板
            headerPanel = new Panel();
            headerPanel.Size = new Size(900, 80);
            headerPanel.BackColor = UIStyleManager.PrimaryColor;
            headerPanel.Dock = DockStyle.Top;

            Label lblTitleIcon = new Label
            {
                Text = IconManager.Icons.Save,
                Font = new Font("Segoe UI Emoji", 24),
                ForeColor = Color.White,
                Location = new Point(30, 20),
                AutoSize = true
            };

            Label titleLabel = new Label
            {
                Text = "医疗卡办理 - 患者信息录入",
                Font = UIStyleManager.TitleFont,
                ForeColor = Color.White,
                Location = new Point(80, 25),
                AutoSize = true
            };

            headerPanel.Controls.Add(lblTitleIcon);
            headerPanel.Controls.Add(titleLabel);

            // 创建内容面板
            contentPanel = new Panel();
            contentPanel.Dock = DockStyle.Fill;
            contentPanel.BackColor = UIStyleManager.BackgroundColor;
            contentPanel.Padding = new Padding(30);
            contentPanel.AutoScroll = true;

            // 创建按钮面板
            buttonPanel = new Panel();
            buttonPanel.Size = new Size(900, 80);
            buttonPanel.BackColor = Color.FromArgb(240, 240, 240);
            buttonPanel.Dock = DockStyle.Bottom;

            CreateFormControls();
            CreateButtons();

            // 添加面板到窗体
            this.Controls.Add(contentPanel);
            this.Controls.Add(buttonPanel);
            this.Controls.Add(headerPanel);
        }

        private void CreateFormControls()
        {
            int yPos = 20;
            int labelWidth = 120;
            int controlWidth = 200;
            int spacing = 45;

            // 姓名
            lblName = CreateLabel("*姓名:", 30, yPos, labelWidth);
            lblName.ForeColor = Color.Red;
            txtName = CreateTextBox(160, yPos, controlWidth);

            // 性别 (右侧)
            lblSex = CreateLabel("*性别:", 400, yPos, labelWidth);
            lblSex.ForeColor = Color.Red;
            
            Panel genderPanel = new Panel
            {
                Location = new Point(530, yPos),
                Size = new Size(150, 30),
                BackColor = Color.Transparent
            };

            rbMale = new RadioButton
            {
                Text = "男",
                Location = new Point(0, 5),
                Size = new Size(50, 25),
                Checked = true,
                Font = UIStyleManager.BodyFont
            };

            rbFemale = new RadioButton
            {
                Text = "女",
                Location = new Point(60, 5),
                Size = new Size(50, 25),
                Font = UIStyleManager.BodyFont
            };

            genderPanel.Controls.Add(rbMale);
            genderPanel.Controls.Add(rbFemale);

            yPos += spacing;

            // 出生日期
            lblBirth = CreateLabel("*出生日期:", 30, yPos, labelWidth);
            lblBirth.ForeColor = Color.Red;
            dtpBirth = new DateTimePicker
            {
                Location = new Point(160, yPos),
                Size = new Size(controlWidth, 30),
                Format = DateTimePickerFormat.Short,
                Font = UIStyleManager.BodyFont
            };

            // 联系电话 (右侧)
            lblContact = CreateLabel("*联系电话:", 400, yPos, labelWidth);
            lblContact.ForeColor = Color.Red;
            txtContact = CreateTextBox(530, yPos, controlWidth);

            yPos += spacing;

            // 身份证号
            lblIdCard = CreateLabel("*身份证号:", 30, yPos, labelWidth);
            lblIdCard.ForeColor = Color.Red;
            txtIdCard = CreateTextBox(160, yPos, 300);
            
            // 添加身份证号提示标签（因为PlaceholderText在.NET Framework中不支持）
            Label lblIdCardHint = new Label
            {
                Text = "格式：18位数字，如 110101199001011234",
                Font = new Font("微软雅黑", 8),
                ForeColor = Color.Gray,
                Location = new Point(160, yPos + 25),
                AutoSize = true
            };

            yPos += spacing + 15; // 为提示文字增加额外的间距

            // 现住址
            lblAddress = CreateLabel("现住址:", 30, yPos, labelWidth);
            txtAddress = CreateTextBox(160, yPos, 500);

            yPos += spacing;

            // 传染病史
            lblInfection = CreateLabel("传染病史:", 30, yPos, labelWidth);
            txtInfectionHistory = CreateTextBox(160, yPos, 500);
            txtInfectionHistory.Multiline = true;
            txtInfectionHistory.Height = 60;
            txtInfectionHistory.ScrollBars = ScrollBars.Vertical;

            yPos += 80;

            // 遗传病信息
            lblGenetic = CreateLabel("遗传病信息:", 30, yPos, labelWidth);
            txtGeneticInfo = CreateTextBox(160, yPos, 500);
            txtGeneticInfo.Multiline = true;
            txtGeneticInfo.Height = 60;
            txtGeneticInfo.ScrollBars = ScrollBars.Vertical;

            yPos += 80;

            // 创建人
            lblCreatePerson = CreateLabel("创建人:", 30, yPos, labelWidth);
            txtCreatePerson = CreateTextBox(160, yPos, controlWidth);
            txtCreatePerson.Text = string.IsNullOrEmpty(currentUserName) ? "管理员" : currentUserName;
            txtCreatePerson.ReadOnly = true;
            txtCreatePerson.BackColor = Color.LightGray;

            // 添加必填字段说明
            Label lblRequired = new Label
            {
                Text = "标记 * 的字段为必填项",
                Font = new Font("微软雅黑", 9),
                ForeColor = Color.Red,
                Location = new Point(30, yPos + 40),
                AutoSize = true
            };

            // 添加身份证号示例按钮
            Button btnIdCardExample = new Button
            {
                Text = "生成示例身份证号",
                Location = new Point(470, yPos - 80 - spacing * 4), // 身份证号输入框右侧
                Size = new Size(120, 30),
                BackColor = Color.LightBlue,
                FlatStyle = FlatStyle.Flat,
                Font = new Font("微软雅黑", 9)
            };
            btnIdCardExample.Click += (s, e) => {
                txtIdCard.Text = GenerateValidIdCard();
            };

            // 添加所有控件到内容面板
            contentPanel.Controls.AddRange(new Control[] {
                lblName, txtName, lblSex, genderPanel,
                lblBirth, dtpBirth, lblContact, txtContact,
                lblIdCard, txtIdCard, lblIdCardHint, btnIdCardExample,
                lblAddress, txtAddress,
                lblInfection, txtInfectionHistory,
                lblGenetic, txtGeneticInfo,
                lblCreatePerson, txtCreatePerson,
                lblRequired
            });
        }

        private Label CreateLabel(string text, int x, int y, int width)
        {
            Label label = new Label
            {
                Text = text,
                Location = new Point(x, y),
                Size = new Size(width, 30),
                Font = UIStyleManager.BodyFont,
                TextAlign = ContentAlignment.MiddleRight,
                ForeColor = UIStyleManager.TextPrimaryColor
            };
            return label;
        }

        private TextBox CreateTextBox(int x, int y, int width)
        {
            TextBox textBox = new TextBox
            {
                Location = new Point(x, y),
                Size = new Size(width, 30),
                Font = UIStyleManager.BodyFont
            };
            UIStyleManager.ApplyTextBoxStyle(textBox);
            return textBox;
        }

        private void CreateButtons()
        {
            // 保存按钮
            btnSave = IconManager.CreateSmallIconButton("保存", IconManager.Icons.Save, 100, 40, ButtonStyle.Success);
            btnSave.Location = new Point(300, 20);

            // 重置按钮
            btnReset = IconManager.CreateSmallIconButton("重置", IconManager.Icons.Refresh, 100, 40, ButtonStyle.Warning);
            btnReset.Location = new Point(420, 20);

            // 取消按钮
            btnCancel = IconManager.CreateSmallIconButton("取消", IconManager.Icons.Close, 100, 40, ButtonStyle.Danger);
            btnCancel.Location = new Point(540, 20);

            buttonPanel.Controls.Add(btnSave);
            buttonPanel.Controls.Add(btnReset);
            buttonPanel.Controls.Add(btnCancel);
        }

        private void SetupEventHandlers()
        {
            btnSave.Click += BtnSave_Click;
            btnReset.Click += BtnReset_Click;
            btnCancel.Click += BtnCancel_Click;
            
            // 设置身份证号的占位符效果
            SetupPlaceholderEffect(txtIdCard, "请输入18位身份证号");
        }

        private void SetupPlaceholderEffect(TextBox textBox, string placeholderText)
        {
            // 初始设置占位符
            if (string.IsNullOrEmpty(textBox.Text))
            {
                textBox.Text = placeholderText;
                textBox.ForeColor = Color.Gray;
            }

            textBox.Enter += (s, e) => {
                if (textBox.Text == placeholderText)
                {
                    textBox.Text = "";
                    textBox.ForeColor = Color.Black;
                }
            };

            textBox.Leave += (s, e) => {
                if (string.IsNullOrEmpty(textBox.Text))
                {
                    textBox.Text = placeholderText;
                    textBox.ForeColor = Color.Gray;
                }
            };
        }



        private async void BtnSave_Click(object sender, EventArgs e)
        {
            if (!ValidateForm())
            {
                return;
            }

            // 禁用保存按钮，防止重复提交
            btnSave.Enabled = false;
            btnSave.Text = "保存中...";

            try
            {
                // 获取实际的身份证号（排除占位符文本）
                string actualIdCard = txtIdCard.Text == "请输入18位身份证号" ? "" : txtIdCard.Text.Trim();
                
                var patientData = new
                {
                    accountId = currentUserId > 0 ? currentUserId : 1001, // 使用当前登录用户ID
                    name = txtName.Text.Trim(),
                    sex = rbMale.Checked,
                    dateOfBirth = dtpBirth.Value.ToString("yyyy-MM-dd"),
                    contactInfo = txtContact.Text.Trim(),
                    idCard = actualIdCard,
                    currentAddress = txtAddress.Text.Trim(),
                    infectiousDiseaseHistory = txtInfectionHistory.Text.Trim(),
                    geneticDiseaseInfo = txtGeneticInfo.Text.Trim(),
                    createPeople = txtCreatePerson.Text.Trim()
                };

                string json = JsonConvert.SerializeObject(patientData, Formatting.Indented);
                
                // 调用API保存数据
                await CallAddPatientApi(json);
                
                MessageBox.Show($"患者信息保存成功！\n\n账户ID: {patientData.accountId}\n姓名: {patientData.name}\n性别: {(patientData.sex ? "男" : "女")}", 
                    "保存成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复保存按钮状态
                btnSave.Enabled = true;
                btnSave.Text = "保存";
            }
        }

        private bool ValidateForm()
        {
            if (string.IsNullOrWhiteSpace(txtName.Text))
            {
                MessageBox.Show("请输入患者姓名", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtName.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtContact.Text))
            {
                MessageBox.Show("请输入联系电话", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtContact.Focus();
                return false;
            }

            string idCardText = txtIdCard.Text;
            if (string.IsNullOrWhiteSpace(idCardText) || idCardText == "请输入18位身份证号")
            {
                MessageBox.Show("请输入身份证号", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtIdCard.Focus();
                return false;
            }

            if (!IsValidIdCard(idCardText))
            {
                MessageBox.Show("请输入正确的身份证号格式\n格式要求：18位数字，最后一位可以是数字或X", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtIdCard.Focus();
                return false;
            }

            // 简单的手机号验证
            if (!System.Text.RegularExpressions.Regex.IsMatch(txtContact.Text, @"^1[3-9]\d{9}$"))
            {
                MessageBox.Show("请输入正确的手机号码", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtContact.Focus();
                return false;
            }

            return true;
        }

        private bool IsValidIdCard(string idCard)
        {
            if (string.IsNullOrEmpty(idCard) || idCard.Length != 18)
                return false;

            // 检查前17位是否为数字
            for (int i = 0; i < 17; i++)
            {
                if (!char.IsDigit(idCard[i]))
                    return false;
            }

            // 检查最后一位是否为数字或X
            char lastChar = idCard[17];
            if (!char.IsDigit(lastChar) && lastChar != 'X' && lastChar != 'x')
                return false;

            // 可以添加更严格的校验码验证
            return ValidateIdCardChecksum(idCard);
        }

        private bool ValidateIdCardChecksum(string idCard)
        {
            try
            {
                // 身份证号码验证权重
                int[] weights = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
                char[] checkCodes = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };

                int sum = 0;
                for (int i = 0; i < 17; i++)
                {
                    sum += (idCard[i] - '0') * weights[i];
                }

                int remainder = sum % 11;
                char expectedCheckCode = checkCodes[remainder];
                char actualCheckCode = char.ToUpper(idCard[17]);

                return expectedCheckCode == actualCheckCode;
            }
            catch
            {
                return false;
            }
        }

        private string GenerateValidIdCard()
        {
            // 生成一个有效的测试身份证号
            Random random = new Random();
            
            // 地区代码 (前6位) - 使用北京的代码
            string areaCode = "110101";
            
            // 出生日期 (8位) - 使用选择的生日
            string birthDate = dtpBirth.Value.ToString("yyyyMMdd");
            
            // 顺序码 (3位) - 随机生成
            string sequenceCode = random.Next(100, 999).ToString();
            
            // 前17位
            string first17 = areaCode + birthDate + sequenceCode;
            
            // 计算校验码
            int[] weights = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
            char[] checkCodes = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };
            
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += (first17[i] - '0') * weights[i];
            }
            
            int remainder = sum % 11;
            char checkCode = checkCodes[remainder];
            
            return first17 + checkCode;
        }

        private void BtnReset_Click(object sender, EventArgs e)
        {
            txtName.Clear();
            txtContact.Clear();
            txtIdCard.Text = "请输入18位身份证号";
            txtIdCard.ForeColor = Color.Gray;
            txtAddress.Clear();
            txtInfectionHistory.Clear();
            txtGeneticInfo.Clear();
            rbMale.Checked = true;
            dtpBirth.Value = DateTime.Now.AddYears(-30); // 默认30岁
            txtCreatePerson.Text = string.IsNullOrEmpty(currentUserName) ? "管理员" : currentUserName;
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        // 实际调用API的方法
        private async System.Threading.Tasks.Task CallAddPatientApi(string jsonData)
        {
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    client.Timeout = TimeSpan.FromSeconds(30); // 设置超时时间
                    
                    // 设置请求头
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Add("Accept", "application/json");
                    client.DefaultRequestHeaders.Add("User-Agent", "HospitalManagementSystem/1.0");
                    
                    var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                    
                    Console.WriteLine($"发送POST请求到: http://101.201.170.32:5166/api/Patient/AddPatient");
                    Console.WriteLine($"请求数据: {jsonData}");
                    
                    var response = await client.PostAsync("http://101.201.170.32:5166/api/Patient/AddPatient", content);
                    string responseContent = await response.Content.ReadAsStringAsync();
                    
                    Console.WriteLine($"响应状态: {response.StatusCode}");
                    Console.WriteLine($"响应内容: {responseContent}");
                    
                    if (!response.IsSuccessStatusCode)
                    {
                        throw new Exception($"API调用失败 - 状态码: {response.StatusCode}\n响应内容: {responseContent}");
                    }
                }
                catch (HttpRequestException httpEx)
                {
                    throw new Exception($"网络请求异常: {httpEx.Message}\n请确认API服务是否正常运行");
                }
                catch (TaskCanceledException timeoutEx)
                {
                    throw new Exception($"请求超时: {timeoutEx.Message}\n请检查网络连接或服务器响应时间");
                }
            }
        }
    }
} 
